package com.smartlight.godlight.utils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class OkHttpUtils {
//    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS) // 连接超时时间
            .readTimeout(30, TimeUnit.SECONDS) // 读取超时时间
            .writeTimeout(30, TimeUnit.SECONDS) // 写入超时时间
            .build();

    public static void get(String url, Callback callback) {
        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(callback);
    }

    public static void post(String url, Map<String, String> params, Callback callback) {
        FormBody.Builder formBuilder = new FormBody.Builder();

        if (params != null){
            for(String key : params.keySet()){
                String value = params.get(key);
                formBuilder.add(key, value);
            }
        }

        // 构建RequestBody
        RequestBody formBody = formBuilder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        client.newCall(request).enqueue(callback);
    }
}
